<template>
  <!-- 数据录入 - 编辑 -->
  <div class="dashboardEdit" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="#fff">
    <div class="main">
      <sticky :sticky-top="Theight" :z-index="10">
        <h1 class="titleH1">
          <div>
            <span>审批流程：</span>
            <el-select v-model="form.approveProcess" placeholder="请选择" class="searchItem">
              <el-option v-for="(item, index) in options" :key="index" :label="item" :value="item" style="font-size:0.16rem;" />
            </el-select>
          </div>
          <div>
            <el-button type="primary" @click="onSubmit('forms', 'submit')">提交</el-button>
            <el-button type="primary" @click="onSubmit('forms', 'hold')">保存</el-button>
            <el-button type="primary" @click="goBack">返回</el-button>
          </div>
        </h1>
      </sticky>
      <div class="content">
        <el-form v-if="form.articleList.length>0" ref="forms" :model="form.articleList[dataIndex]" :rules="rules" label-width="1.2rem">
          <div class="content-warpper">
            <div class="left">
              <div class="left-warpper">
                <h2 class="titleH2"><span class="line">图文基本信息</span></h2>
                <p>
                  <span>图文类别：</span>
                  <el-select v-model="imageTextType" placeholder="请选择" @change="selectChange">
                    <el-option label="单图文" value="single" />
                    <el-option label="多图文" value="many" />
                  </el-select>
                </p>
                <Kanban :key="1" :list="imageTextList" :image-text-type="imageTextType" class="kanban" />
                <el-button v-if="imageTextType=='many'" icon="el-icon-plus" @click="addImageText">添加</el-button>
              </div>
            </div>
            <div class="right">
              <el-form-item label="标题" prop="title">
                <el-input v-model.trim="form.articleList[dataIndex].title" placeholder="不超过80字符" maxlength="80" @change="titleChange" />
              </el-form-item>
              <el-form-item label="作者（选填）" prop="author">
                <el-input v-model.trim="form.articleList[dataIndex].author" placeholder="作者（选填）" />
              </el-form-item>
              <el-form-item prop="fileList">
                <span slot="label">封面&nbsp;<span style="color:#B9B9B9;">&nbsp;大图片建议尺寸：540像素*300像素</span></span>
                <el-upload
                  ref="uploads"
                  class="upload-demo"
                  :action="action"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :file-list="form.articleList[dataIndex].fileList"
                  list-type="picture"
                  :limit="1"
                  :auto-upload="false"
                >
                  <el-button :icon="uploadLoading?'el-icon-loading':'el-icon-plus'" style="width:100%;" :disabled="form.articleList[dataIndex].fileList.length>0">{{uploadLoading?'上传中...':'上传封面'}}</el-button>
                </el-upload>
              </el-form-item>
              <el-switch v-model="form.articleList[dataIndex].showCoverPic" style="margin-bottom: 0.1rem;" active-color="#13ce66" active-text="封面图片显示在正文中" />
              <el-form-item label="摘要" prop="digest">
                <el-input v-model.trim="form.articleList[dataIndex].digest" type="textarea" placeholder="请输入内容" maxlength="150" show-word-limit />
              </el-form-item>
              <div v-for="(item, index) in form.articleList" :key="index">
                <el-form-item v-show="index == dataIndex" label="" prop="content">
                  <tinymce :id="`tinymce${index}`" v-model="form.articleList[dataIndex].content" :height="300" />
                </el-form-item>
              </div>
            </div>
          </div>
          <div class="content-warpper two">
            <h2 class="titleH2">
              <span class="line">图文发布信息</span>
            </h2>
            <el-form-item label="终端类别：" prop="terminalType" class="terminalType">
              <el-checkbox-group v-model="form.terminalType" :false-label="falseLabel" @change="checkboxGroup">
                <el-checkbox v-for="(item, index) in options2" :key="index" :label="item.code">{{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <div class="content">
              <div v-for="(item, index) in checkTable" :key="index" class="terminal"  v-show="form.terminalType.includes(item.key)">
                <p><svg-icon icon-class="right" style="color:#516FE9;"/> {{ item.label }}</p>
                <el-table v-if="form.terminalType.includes(item.key)" :ref="`${item.key}Table`" :data="item.data" border style="width: 100%" @select="selection(item.key)" @selection-change="selectionChange" @select-all="selection(item.key)">
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column type="index" width="55" label="序号" align="center" />
                  <el-table-column v-for="(data, key) in item.header" :key="key" :prop="data.key" :label="data.label" align="center" />
                </el-table>
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import Sticky from '@/components/Sticky'
import Tinymce from '@/components/Tinymce'
import Kanban from '../components/editKanban'
import { bus } from '@/main'

export default {
  name: 'DashboardEdit',
  components: { Sticky, Tinymce, Kanban },
  data() {
    const valiFile = (rule, value, callback) => {
      if (value.length == '0') {
        callback(new Error('请上传封面'))
      } else {
        callback()
      }
    }
    const validDigest = (rule, value, callback) => {
      if (this.imageTextType == 'single') {
        if (value === '') {
          callback(new Error('请输入摘要信息'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const validCheck = (rule, value, callback) => {
      if (this.form.terminalType.length == '0') {
        callback(new Error('请选择终端类别'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      Theight: 0,
      options: [], // 审批流程下拉框
      options2: [], // 终端类型
      dataID: 0,
      form: {
        id: '',
        approveProcess: '', // 审批流程
        articleList: [], // 图文数据
        terminalType: [], // 图文发布信息 - 终端类别 多选
        wxList: [], // 微信公众号终端
        ydList: [], // 移动服务平台终端
        otherList: [], // 其他软件平台终端
        hardwareList: [] // 硬件终端终端
      },
      imageTextType: 'single', // 单图文 / 多图文
      checkTable: [], // 图文发布信息 - 终端类别 table
      imageTextList: [], // 图文基本信息列表
      terminalList: { // 终端列表
        wxList: [], // 微信
        ydList: [], // 移动服务平台
        otherList: [], // 其他软件平台
        hardwareList: [] // 硬件终端
      },
      falseLabel: [],
      dataIndex: 0, // 当前选中编辑的图文
      tableIndex: '', // 当前选中的终端
      rules: {
        title: [
          { required: true, message: '请输入网页名称', trigger: 'change' }
        ],
        author: [
          { required: false, message: '请输入网页名称', trigger: 'change' }
        ],
        fileList: [
          { required: true, validator: valiFile, trigger: 'blur' }
        ],
        digest: [
          { validator: validDigest, trigger: 'change' }
        ],
        content: [
          { required: true, message: '图文内容不能为空', trigger: 'change' }
        ],
        terminalType: [
          { required: true, validator: validCheck, trigger: 'change' }
        ]
      },
      editData: '',
      uploadLoading: false,
      status: false, // 离开页面时，判断是否确认离开
      count: 0 // 判断页面是否有过数据更改
    }
  },
  computed: {
    action() {
      const api = `${process.env.VUE_APP_BASE_API}/common/uploadFile`
      return api
    }
  },
  created() {
    this.init()
    bus.$on('imageTextChangeEdit', (msg) => {
      for (const i in this.form.articleList) {
        if (msg.key == this.form.articleList[i].dataID) {
          this.dataIndex = i
        }
      }
      if (msg.type != '' && msg.type == 'delete') {
        this.form.articleList.splice(this.dataIndex, 1)
        this.imageTextList.splice(this.dataIndex, 1)
        const str = JSON.parse(JSON.stringify(this.form.articleList[0].content))
        tinyMCE.activeEditor.setContent(str)
      } else {
        const str = JSON.parse(JSON.stringify(this.form.articleList[this.dataIndex].content))
        tinyMCE.activeEditor.setContent(str)
      }
    })
  },
  mounted() {
    this.Theight = document.getElementById('Theader').offsetHeight
  },
  // 页面数据有更新时触发
  updated: function() {
    this.count++
  },
  // 如有更改，离开页面则弹出提示框
  beforeRouteLeave(to, from, next) {
    if (this.count > 1) { //
      if (this.status) {
        return next()
      } else {
        this.$confirm('是否放弃当前修改内容?', '提示', {
          confirmButtonText: '放弃修改',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.status = true
          return next()
        }).catch(() => {
          this.status = false
          return next(false)
        })
      }
    } else {
      next()
    }
  },
  beforeDestroy() {
    this.$refs.forms.resetFields();
    tinymce.remove();
    location.reload();
  },
  methods: {
    init() {
      const id = this.$route.query.id
      this.$api.imageTextDetail({ id: id }).then((response) => {
        if (response.data.status == 1) {
          this.editData = JSON.parse(JSON.stringify(response.data.data))
          const list = this.editData.mediaNews.articleList
          if (list.length > 1) {
            this.imageTextType = 'many'
          }
          this.form.articleList = []
          this.imageTextList = []
          for (let i = 0; i < list.length; i++) {
            this.addImageText()
            setTimeout(() => {
              this.loading = false
              this.imageTextList[i].title = list[i].title
              this.imageTextList[i].src = list[i].picUrl
              this.form.articleList[i].author = list[i].author
              this.form.articleList[i].content = list[i].content
              this.form.articleList[i].digest = list[i].digest
              this.form.articleList[i].fileId = list[i].fileId
              this.form.articleList[i].id = list[i].id
              this.form.articleList[i].title = list[i].title
              this.form.articleList[i].fileList.push({ name: list[i].picName, url: list[i].picUrl })
              this.form.articleList[i].showCoverPic = list[i].showCoverPic == '1'
              tinyMCE.activeEditor.setContent(list[i].content)
            }, 1000)
          }
          this.form.id = this.editData.id
          this.form.approveProcess = this.editData.approveProcess
          this.form.terminalType = this.editData.terminalType.split(',')
          this.$api.getApproveProcess().then(response => { // 审批流程下拉框
            if (response.data.status == 1) {
              this.options = response.data.data
            } else {
              this.$message.error(response.data.msg)
            }
          })
          this.$api.getTerminal().then((response) => { // 请求终端类型
            if (response.data.status == 1) {
              this.options2 = response.data.data
            } else {
              this.$message.error(response.data.msg)
            }
          })
          this.$api.getTerminalList().then((response) => { // 请求终端列表
            if (response.data.status == 1) {
              this.terminalList = response.data.data
              this.checkTableFN()
              const arr = []
              const _this = this
              setTimeout(() => {
                _this.form.terminalType.forEach(item => {
                  const key = item
                  const id = _this.editData[key].split(',')
                  const list = _this.terminalList[key]
                  _this.tableIndex = key
                  _this.form[key] = id
                  list.forEach(data => {
                    if (id.includes(JSON.stringify(data.id))) {
                      _this.$refs[`${key}Table`][0].toggleRowSelection(data)
                    }
                  });
                });
              }, 100)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    // 单图文/多图文切换
    selectChange(val) {
      const list = this.imageTextList
      // this.$refs.forms.resetFields();
      if (val == 'single') {
        for (const i in list) {
          if (i == this.dataIndex) {
            this.imageTextList[i].show = true
          } else {
            this.imageTextList[i].show = false
          }
        }
      } else {
        for (const i in list) {
          this.imageTextList[i].show = true
        }
      }
    },
    // 多图文-添加
    addImageText() {
      this.imageTextList.push({ title: `标题`, dataID: this.dataID, src: '', show: true })
      this.form.articleList.push(
        {
          title: '', // 标题
          dataID: this.dataID,
          author: '', // 作者
          fileList: [], // 封面
          fileId: '', // 封面
          showCoverPic: false, // 封面图片显示在正文中
          digest: '', // 摘要
          content: '' // 富文本内容
        }
      )
      this.dataID++
    },
    // 图文标题
    titleChange(val) {
      this.imageTextList[this.dataIndex].title = val
    },
    // 移除文件
    handleRemove(file, fileList) {
      this.form.articleList[this.dataIndex].fileList = fileList
      this.imageTextList[this.dataIndex].src = ''
    },
    // 文件校验
    handleChange(file, fileList) {
      // 文件类型、大小判断
      this.reg = /(.*)\.(jpg|bmp|jpeg|png)$/ // 图片
      this.fileSize = 5 // 5M
      if ((file.size / 1024 / 1024) <= this.fileSize && this.reg.test(file.name)) {
        this.form.articleList[this.dataIndex].fileList = fileList
        this.imageTextList[this.dataIndex].src = file.url
        this.customUpload({file: file.raw})
      } else {
        fileList.splice(-1, 1) // 删除不符合要求的文件
        this.form.articleList[this.dataIndex].fileList = fileList
        return this.$message.error('暂不支持上传该类型文件，请重新选择！')
      }
    },
    // 上传文件
    customUpload(file) {
      const data = new FormData()
      data.append('files', file.file)
      this.uploadLoading = true
      this.$api.upload(data).then((response) => {
        if (response.data.status == 1) {
          this.uploadLoading = false
          this.form.articleList[this.dataIndex].fileId = response.data.data
          this.$message.success('上传成功！')
        } else {
          this.uploadLoading = false
          this.form.articleList[this.dataIndex].fileList = []
          this.form.articleList[this.dataIndex].fileId = ''
          this.$message.error('上传失败，请重试！')
        }
      }).catch(() => {
        this.uploadLoading = false
        this.form.articleList[this.dataIndex].fileList = []
        this.form.articleList[this.dataIndex].fileId = ''
        this.$message.error('上传失败，请重试！')
      })
    },
    // 发布终端table
    checkTableFN() {
      this.checkTable = [
        {
          label: '微信公众号',
          key: 'wxList',
          header: [
            { label: '微信公众号名称', key: 'name' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.wxList
        },
        {
          label: '移动服务平台',
          key: 'ydList',
          header: [
            { label: '移动服务平台名称', key: 'name' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.ydList
        },
        {
          label: '其他软件终端',
          key: 'otherList',
          header: [
            { label: '软件终端名称', key: 'name' },
            { label: '栏目', key: 'section' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.otherList
        },
        {
          label: '硬件终端',
          key: 'hardwareList',
          header: [
            { label: '硬件终端名称', key: 'name' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.hardwareList
        }
      ]
    },
    // 终端类别
    checkboxGroup(val) {
      const keyArr = Object.keys(this.terminalList)
      keyArr.forEach(item => {
        if (!this.form.terminalType.includes(item)) {
          this.form[item] = []
        }
      });
    },
    selection(key) {
      this.tableIndex = key
    },
    selectionChange(data) {
      setTimeout(async () => {
        const arr = []
        await data.forEach(item => {
          arr.push(item.id)
        });
        this.form[this.tableIndex] = arr;
      }, 50)
    },
    // 保存/提交
    onSubmit(formName, val) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 校验勾选的终端类别，有没有选对应的终端
          const checkList = this.form.terminalType
          let num = false
          await checkList.forEach(item => {
            if (this.form[item].length>0) {
              num = true
            } else {
              num = false
              return this.$message.error('请选择需发布的终端')
            }
          });
          if (num) {
            const obj = {
              id: this.form.id,
              approveProcess: this.form.approveProcess,
              articleList: this.form.articleList,
              terminalType: this.form.terminalType,
            }
            checkList.forEach(key => {
              obj[key] = this.form[key].join(',');
            });
            if (obj.terminalType.length == 1) {
              obj.terminalType = obj.terminalType[0]
            } else {
              for (const i in obj.terminalType) {
                const key = obj.terminalType[i]
              }
              obj.terminalType = obj.terminalType.join(',')
            }
            if (val == 'hold') {
              this.loading = true
              this.$api.imageTextUpdata(obj).then((response) => {
                if (response.data.status == 1) {
                  this.loading = false
                  this.$message.success(response.data.msg)
                  this.count = 0
                  this.status = true
                  this.$router.push('/Dashboard/dataAcquisition');
                } else {
                  this.loading = false
                  this.$message.error(response.data.msg)
                }
              }).catch(() => this.loading = false)
            } else if (val == 'submit') {
              this.loading = true
              this.$api.submitImageList(obj).then((response) => {
                if (response.data.status == 1) {
                  this.loading = false
                  this.$message.success(response.data.msg)
                  this.count = 0
                  this.status = true
                  this.$router.push('/Dashboard/dataAcquisition');
                } else {
                  this.loading = false
                  this.$message.error(response.data.msg)
                }
              }).catch(() => this.loading = false)
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    goBack() {
      this.$router.push('/Dashboard/dataAcquisition');
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboardEdit {
  width: 100%;
  background: #fff;
  box-shadow: #ccc 0 0 10px 0px;
  border-radius: 0.05rem;
  >>>*{ font-size: 0.16rem}
  .main {
    position: relative;
    .titleH1 {
      width: 100%;
      display: flex;
      align-items: center;
      font-size: 0.18rem;
      margin: 0;
      height: 0.55rem;
      justify-content: space-between;
      font-weight: normal;
      border-bottom: 1px solid #ccc;
      padding: 0.1rem 0.2rem;
      background: #fff;
      >div{
        height: 100%;
        display: flex;
        align-items: center;
      }
      >div:nth-of-type(2){
        height: 100%;
        .el-button {
          width: 1rem;
          height: 0.35rem;
          padding: 0.09rem 0.15rem;
        }
        .el-button:nth-of-type(1),
        .el-button:nth-of-type(2) {
          margin-right: 0.2rem;
        }
      }
    }
    .titleH2 {
      height: 0.65rem;
      margin: 0;
      padding: 0.2rem;
      display: flex;
      align-items: center;
      .line{
        position: relative;
        padding-left: 0.1rem;
      }
      .line::before {
        content: '';
        background: #536FEA;
        width: 0.03rem;
        height: 0.2rem;
        display: inline-block;
        position: absolute;
        top: -6%;
        left: 0;
        border-radius: 0.03rem;
      }
    }
    .terminalType {
      width: 100%;
      padding: 0 0.2rem;
      >>>.el-checkbox-group {
        width: 80%;
        display: inline-block;
      }
    }
    .content {
      padding: 0.2rem;
      min-height: 5rem;
      position: relative;
      overflow: hidden;
      .content-warpper {
        position: relative;
        background: #F8F8F8;
        .left {
          width: 4rem;
          text-align: center;
          padding-right: 0.2rem;
          position: absolute;
          overflow: hidden;
          overflow-y: auto;
          height: 100%;
          background: #fff;
          .left-warpper {
            width: 100%;
            height: 100%;
            >p {
              text-align: left;
            }
            >.el-button {
              width: 60%;
            }
          }
        }
        .right {
          padding: 0.1rem 0.2rem 0;
          box-sizing: border-box;
          margin-left: 4rem;
          overflow: hidden;
          >>>.el-form-item {
            margin-bottom: 0.2rem;
            .el-form-item__label {
              float: none;
            }
            .el-form-item__content {
              margin-left: 0 !important;
              .upload-demo {
                .el-upload {
                  width: 100%;
                }
              }
            }
          }
        }
        .titleH2 {
          height: 0.45rem;
          margin: 0;
          padding: 0.1rem 0rem;
          border: none;
        }
        .terminalType {
          width: 100%;
          padding: 0 0.2rem;
          >>>.el-checkbox-group {
            width: 80%;
            display: inline-block;
          }
        }
        .terminal {
          background: #F8F8F8;
          padding: 0.1rem 0.2rem;
          min-height: 2rem;
        }
      }
      .two {
        margin-top: 0.2rem;
        background: #fff;
        border-top: 1px solid #ccc;
      }
    }
    .flex-column {
      display: flex;
      flex-flow: column;
    }
    .flex {
      display: flex;
    }
  }
}
</style>
